import { lrc } from '../../assets/js/data'
import musicLiving from '../../assets/audio/music.mp3'
import { useEffect, useRef, useState } from 'react'
import './styles.scss'

const LIHEIGHT = 50

const Music: React.FC = () => {
  const [musicWord, setMusicWord] = useState<{ time: number, words: string }[]>([])
  const [index, setIndex] = useState(-1)
  const [moveHeight, setMoveHeight] = useState(0)
  const moveIndex = useRef(0)

  useEffect(() => {
    conversionMusicStr()
  }, [])

  const conversionMusicStr = () => {
    let arr: any[] = lrc.split('\n')
    arr = arr.map(item => ({
      time: conversionTime(item.slice(1).split(']')[0]),
      words: item.slice(1).split(']')[1]
    }))
    setMusicWord(arr)
  }

  const conversionTime = (time: string): number => {
    const arr = time.split(':')
    return Number(arr[0]) * 60 + Number(arr[1])
  }

  const getMusicWordIndex = (time: number): number => {
    for (let i = 0; i < musicWord.length; i++) {
      if (musicWord[i].time > time) {
        return i - 1
      }
    }
    return musicWord.length - 1
  }

  const audioChange = (time: number) => {
    const idx = getMusicWordIndex(time)
    setIndex(idx)
    if (idx > 5 && idx !== index) {
      setMoveHeight(LIHEIGHT * moveIndex.current)
      moveIndex.current = moveIndex.current + 1
    }
  }

  return (
    <div className='music-container'>
      <audio
        controls
        src={musicLiving}
        onTimeUpdate={(e) => { audioChange(JSON.parse(JSON.stringify((e.target as any)?.currentTime))) }}
      />
      <div className='list'>
        <ul
          style={{
            transform: `translateY(${-moveHeight}px)`
          }}
        >
          {musicWord.map((item, idx) => (
            <li
              key={item.time}
              className={index === idx ? 'active' : ''}
            >
              {item.words}
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

export default Music